package handler

import (
	"encoding/json"
	"fmt"
	"post-check/cache"
	"post-check/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func List(c *gin.Context) {
	var post []models.Post
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &post)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": post,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id = ?", id).Delete(&models.Post{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	//删除缓存
	redis_key := "post_add" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	info := c.PostForm("info")
	if title == "" || info == "" {
		c.JSON(300, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.Post{
		Model: gorm.Model{},
		Title: title,
		Info:  info,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "post_add" + strconv.Itoa(int(data.ID))
	var post models.Post
	models.DB.Where("id=?", data.ID).First(&post)
	jsonData, _ := json.Marshal(post)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	fmt.Println(data.ID)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

}
